#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2021 Arm Limited or its affiliates and Contributors. All rights reserved.

[[ "$TRACE" ]] && set -x
set -euo pipefail
shopt -s extglob

rand_int_inclusive() {
    MIN=$1
    MAX=$2
    echo $(( RANDOM * ( (MAX+1) - MIN ) / 32768 + MIN ))
}

rand_filename() {
    # Max 8^2 possible filenames
    CHARS=(a b c d 1 2 3 4)
    CHAR1="$(rand_int_inclusive 0 7)"
    CHAR2="$(rand_int_inclusive 0 7)"
    echo "${CHARS[$CHAR1]}${CHARS[$CHAR2]}"
}

rand_bytes() {
  dd if=/dev/urandom bs="$1" count=1 iflag=fullblock
}

create_rand_file() {
    APPROX_FILE_SIZE=$1

    DEPTH="$(rand_int_inclusive 1 2)"
    for I in $(seq $DEPTH); do
        DIR_NAME="$(rand_filename)"
        DIR_NAME="${DIR_NAME:0:$I}" # Limit dir name to depth
        if [ ! -f ./"$DIR_NAME" ]; then
            mkdir -p ./"$DIR_NAME"
            cd ./"$DIR_NAME"
        fi
    done

    FILE_SIZE="$(rand_int_inclusive 1 $APPROX_FILE_SIZE)"
    FILE_NAME="$(rand_filename)"
    if [ ! -d ./"$FILE_NAME" ]; then
        rand_bytes "$FILE_SIZE" 2>/dev/null > ./"$FILE_NAME"
    fi
}

main() {
    if [[ $# != 3 ]]; then
        echo "Usage: ./create-test-pack.sh ELFSHAKER_BIN NUM_SNAPSHOTS APPROX_FILE_SIZE"
        echo
        echo "Creates a packfile for testing purposes with random content, intended for consumption by test-scripts/check.sh"
        exit 1
    fi

    ELFSHAKER_BIN=$(realpath $1)
    NUM_SNAPSHOTS=$2
    APPROX_FILE_SIZE=$3

    REPO_DIR="$(mktemp -p /dev/shm/ -d elfshaker.create_test_pack.XXXXXXXXXX)"
    cd "$REPO_DIR"
    mkdir elfshaker_data

    for I in $(seq $NUM_SNAPSHOTS); do
        NUM_FILES=64
        for J in $(seq $NUM_FILES); do
            (create_rand_file $APPROX_FILE_SIZE)
        done
        # Delete some files.
        find \( -name elfshaker_data -prune \) -o -type f -print | sort -R | head -n $(rand_int_inclusive 0 $NUM_FILES) | xargs rm -f
        "${ELFSHAKER_BIN}" store "SNAPSHOT-$I" --verbose
    done

    rm -r -- !("elfshaker_data")
    "${ELFSHAKER_BIN}" pack verification --frames 2 --verbose >/dev/null

    echo "$REPO_DIR"/elfshaker_data/packs/verification.pack
}

main $@
